package com.example.spider.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @author lym
 */
@Configuration
public class RestTemplateConfiguration {

    @Primary
    @Bean("restTemplateUtf8")
    public RestTemplate restTemplate(ProxyableClientHttpRequestFactory randomProxyClientHttpRequestFactory) {
        RestTemplate restTemplate = getInstance(StandardCharsets.UTF_8);
        restTemplate.setRequestFactory(randomProxyClientHttpRequestFactory);
        return restTemplate;
    }

    @Configuration
    public static class StringHttpMessageConverterConfiguration {
        @Bean
        public StringHttpMessageConverter stringHttpMessageConverter(Environment environment) {
            StringHttpMessageConverter converter = new StringHttpMessageConverter(StandardCharsets.UTF_8);
            converter.setWriteAcceptCharset(false);
            return converter;
        }

    }

    public static RestTemplate getInstance(Charset charset) {
        RestTemplate restTemplate = new RestTemplate();
        List<HttpMessageConverter<?>> list = restTemplate.getMessageConverters();
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i) instanceof StringHttpMessageConverter) {
                list.set(i, new AdapterStringHttpMessageConverter(charset));
                break;
            }
        }
        return restTemplate;
    }
}
